import { useMemo } from 'react';
import type { ProColumns } from '@ant-design/pro-components';
import type { ActionType } from '@ant-design/pro-components';
import { Space } from 'antd';

export interface ColumnAction<T = any> {
  /** 按钮文本 */
  text: string;
  /** 按钮类型 */
  type?: 'link' | 'primary' | 'danger';
  /** 按钮点击事件 */
  onClick: (record: T, action: ActionType | undefined) => void;
  /** 是否显示 */
  show?: (record: T) => boolean;
  /** 按钮宽度，默认根据文字长度计算 */
  width?: number;
}

interface UseColumnOptionsOptions<T> {
  /** 操作列标题 */
  title?: string;
  /** 操作列宽度，如果不指定则自动计算 */
  width?: number | string;
  /** 操作按钮配置 */
  actions: ColumnAction<T>[];
  /** 表格实例 */
  actionRef?: React.MutableRefObject<ActionType | undefined>;
  /** 是否固定在右侧 */
  fixed?: boolean;
}

/**
 * 计算操作列宽度
 * @param actions 操作按钮配置
 * @returns 操作列宽度
 */
const calculateOptionsWidth = (actions: ColumnAction<any>[]): number => {
  // 计算所有按钮的宽度总和
  const totalWidth = actions.reduce((sum, action) => {
    // 如果指定了宽度，使用指定的宽度
    if (action.width) {
      return sum + action.width;
    }
    // 否则根据文字长度计算宽度：每个中文字符16px，其他字符8px，加上padding和margin
    const textWidth = Array.from(action.text).reduce((w, char) => {
      return w + (/[\u4e00-\u9fa5]/.test(char) ? 16 : 8);
    }, 0);
    return sum + textWidth
  }, 0);

  // 加上按钮之间的间距：(按钮数量 - 1) * 8px
  const spacingWidth = Math.max(0, actions.length - 1) * 8;
  // 最小宽度100px，最大宽度200px
  return Math.max(60, Math.max(100, totalWidth + spacingWidth + 16)); // 16px for container padding
};

/**
 * 处理表格操作列的 Hook
 * @template T - 表格数据类型
 */
const useColumnOptions = <T extends Record<string, any>>(
  options: UseColumnOptionsOptions<T>
) => {
  const {
    title = '操作',
    width,
    actions = [],
    actionRef,
    fixed = true,
  } = options;

  const optionColumn = useMemo<ProColumns<T>>(() => ({
    title,
    dataIndex: 'option',
    valueType: 'option',
    // width: width || calculateOptionsWidth(actions),
    fixed: fixed ? 'right' : undefined,
    align: 'center',
    render: (_, record) => {
      const visibleActions = actions.filter(
        action => !action.show || action.show(record)
      );

      return (
        <Space size={8} style={{width:calculateOptionsWidth(actions)}}>
          {visibleActions.map((action, index) => {
            const type = action.type || 'link';
            const style = type === 'danger' ? { color: '#ff4d4f',display:'inline-block' } : {
              display:'inline-block'
            };

            return (
              <a
                key={index}
                style={style}
                onClick={() => action.onClick(record, actionRef?.current)}
              >
                {action.text}
              </a>
            );
          })}
        </Space>
      );
    },
  }), [title, width, actions, actionRef, fixed]);

  return {
    optionColumn,
  };
};

export default useColumnOptions; 